package com.jzt.gateway.collect;

import com.jzt.gateway.GlobalConstant;
import com.jzt.gateway.dto.request.AccountRegisterReq;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.net.MalformedURLException;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/06/30 17:53 <br/>
 */
@Component
@Slf4j
public class DefaultCollectRegisterData implements ICollectRegisterData {

    @Override
    public int order() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean support(ServerWebExchange exchange) {
        return true;
    }

    @Override
    public AccountRegisterReq getAccountRegister(ServerWebExchange exchange) {
        final String nameParamName = "name";
        final String passwordParamName = "pwd";
        final String telephoneParamName = "telephone";
        final String emailParamName = "email";
        String body = exchange.getAttribute(GlobalConstant.CACHED_REQUEST_BODY_STR_ATTR);
        JSONObject jsonBody = new JSONObject(body);
        AccountRegisterReq accountRegisterReq = new AccountRegisterReq();
        accountRegisterReq.setLoginName(jsonBody.has(nameParamName) ? jsonBody.getString(nameParamName) : null);
        accountRegisterReq.setLoginPwd(jsonBody.has(passwordParamName) ? jsonBody.getString(passwordParamName) : null);
        accountRegisterReq.setTelephone(jsonBody.has(telephoneParamName) ? jsonBody.getString(telephoneParamName) : null);
        accountRegisterReq.setEmail(jsonBody.has(emailParamName) ? jsonBody.getString(emailParamName) : null);
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        accountRegisterReq.setHttpMethod(serverHttpRequest.getMethodValue());
        try {
            accountRegisterReq.setHttpQueryStr(exchange.getRequest().getURI().toURL().getQuery());
        } catch (MalformedURLException e) {
            log.info("读取QueryString失败", e);
        }
        accountRegisterReq.setHttpBody(body);
        return accountRegisterReq;
    }
}
